#include "common/common.h"



int main(int argc, char** argv){
    int opt;
    int port;
    if(argc != 3){
        fprintf(stderr, "Usage : %s -p port\n", argv[0]);
        exit(1);
    }
    while((opt = getopt(argc, argv, "p:")) != -1){
        switch(opt){
            case 'p':
                port = atoi(optarg);
                break;
            default:
                fprintf(stderr, "Usage : %s -p port\n", argv[0]);
                exit(1);
        }
    }



    int listenfd = server_init(port);
    if(listenfd < 0){
        perror("server_init");
        exit(1);
    }
    DBG(BLUE"listening...\n"NONE);

    FILE* fp = fopen("file", "w");
    if(fp == NULL){
        perror("fopen");
        exit(1);
    }
    DBG(BLUE"file open success\n"NONE);

    struct sockaddr_in client;
    socklen_t len = sizeof(client);
    bzero(&client, sizeof(client));
    int confd = accept(listenfd, (struct sockaddr*)&client, &len);
    if(confd < 0){
        perror("accept");
        exit(1);
    }
    char ip[30] = {0};
    DBG(BLUE"accept from client %s in port %d\n"NONE,inet_ntop(AF_INET, &client.sin_addr, ip, sizeof(ip)), ntohs(client.sin_port));
    DBG(BLUE"accept success\n"NONE);
    DBG(BLUE"confd is %d\n"NONE, confd);

    uint64_t file_size = 0;
    int retval = 0;
    if((retval = recv(confd,(void*)&file_size, sizeof(uint64_t), 0)) <= 0){
        perror("recv");
        exit(1);
    }
    DBG(BLUE"retval : %d\n"NONE, retval);
    DBG(BLUE"file_size : %ld\n"NONE, file_size);
   
    
    close(confd);
    fclose(fp);

    return 0;
}
